package com.raceway.ihcenterapp.web;

import com.raceway.ihcenterapp.domain.Audio;
import com.raceway.ihcenterapp.domain.HelpRequest;
import com.raceway.ihcenterapp.domain.IHS;
import com.raceway.ihcenterapp.domain.Person;
import com.raceway.ihcenterapp.domain.UserRole;
import com.raceway.ihcenterapp.domain.Video;

import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Iterator;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.joda.time.format.DateTimeFormat;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.roo.addon.web.mvc.controller.RooWebScaffold;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

@RooWebScaffold(path = "audios", formBackingObject = Audio.class,delete=false,update=false,create=false)
@RequestMapping("/audios")
@Controller
public class AudioController {
	
	UserDetails user;
	Collection<GrantedAuthority> authorities;
	Iterator<GrantedAuthority> roles;
	String role;
	UserRole  userRoles;
	Person person;
	@PersistenceContext
	private EntityManager em;
	
    @RequestMapping(value = "/findhelprequestaudios/{id}", method = RequestMethod.GET)
    public String audiosOfHelpRequest(@PathVariable("id") Long id, Model model) {

        HelpRequest helpRequest=HelpRequest.findHelpRequest(id);

        model.addAttribute("audios", Audio.findAudiosByHelpRequestId(helpRequest).getResultList());
        return "audios/list";
    }
	@RequestMapping(method = RequestMethod.POST)
    public String create(@Valid Audio audio, BindingResult result, Model model, HttpServletRequest request) {
        if (result.hasErrors()) {
            model.addAttribute("audio", audio);
            addDateTimeFormatPatterns(model);
            return "audios/create";
        }
        audio.persist();
        return "redirect:/audios/" + encodeUrlPathSegment(audio.getId().toString(), request);
    }

	@RequestMapping(params = "form", method = RequestMethod.GET)
    public String createForm(Model model) {
        model.addAttribute("audio", new Audio());
        addDateTimeFormatPatterns(model);
        return "audios/create";
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String show(@PathVariable("id") Long id, Model model) {
        addDateTimeFormatPatterns(model);
        model.addAttribute("audio", Audio.findAudio(id));
        model.addAttribute("itemId", id);
        return "audios/show";
    }

	@RequestMapping(method = RequestMethod.GET)
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model model) {
		user=(UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		authorities=user.getAuthorities();
		roles=authorities.iterator();
		role=roles.next().toString();
		
		if(role.equalsIgnoreCase(userRoles.ROLE_IHS_USER.toString())){
			Query query = Person.findPeopleByUserName(user.getUsername());
			person = (Person) query.getSingleResult();
			IHS ihs=person.getWorkedIHS();
			query=em.createQuery("SELECT Audio FROM Audio audio JOIN audio.HelpRequestId helprequest WHERE helprequest.assignedASI1=:ihs",Audio.class);
			query.setParameter("ihs", ihs);
			 model.addAttribute("audios", query.getResultList());
			
		}else{
		
		
		if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            model.addAttribute("audios", Audio.findAudioEntries(page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));
            float nrOfPages = (float) Audio.countAudios() / sizeNo;
            model.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            model.addAttribute("audios", Audio.findAllAudios());
        }
        addDateTimeFormatPatterns(model);
		}
        return "audios/list";
    }
	@RequestMapping(method = RequestMethod.PUT)
    public String update(@Valid Audio audio, BindingResult result, Model model, HttpServletRequest request) {
        if (result.hasErrors()) {
            model.addAttribute("audio", audio);
            addDateTimeFormatPatterns(model);
            return "audios/update";
        }
        audio.merge();
        return "redirect:/audios/" + encodeUrlPathSegment(audio.getId().toString(), request);
    }

	@RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET)
    public String updateForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute("audio", Audio.findAudio(id));
        addDateTimeFormatPatterns(model);
        return "audios/update";
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model model) {
        Audio.findAudio(id).remove();
        model.addAttribute("page", (page == null) ? "1" : page.toString());
        model.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/audios?page=" + ((page == null) ? "1" : page.toString()) + "&size=" + ((size == null) ? "10" : size.toString());
    }

	@ModelAttribute("helprequests")
    public Collection<HelpRequest> populateHelpRequests() {
        return HelpRequest.findAllHelpRequests();
    }

	void addDateTimeFormatPatterns(Model model) {
        model.addAttribute("audio_audiodate_date_format", DateTimeFormat.patternForStyle("S-", LocaleContextHolder.getLocale()));
    }

	String encodeUrlPathSegment(String pathSegment, HttpServletRequest request) {
        String enc = request.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        }
        catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }
	
	
	
}
